//
//  RunInfoDao.m
//  SportSocial
//
//  Created by yull on 15/2/4.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "RunInfoDao.h"

@implementation RunInfoDao

+ (instancetype)shareInstance
{
    static RunInfoDao *runDao = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        runDao = [[RunInfoDao alloc] init];
    });
    return runDao;
}

- (void)createTable
{
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        NSMutableArray *sqlArray = [NSMutableArray arrayWithObjects:
                                    @"CREATE TABLE IF NOT EXISTS runInfo ("
                                    "[id] integer NOT NULL PRIMARY KEY AUTOINCREMENT, "
                                    "[planId] integer,"
                                    "[locate_date] integer,"
                                    "[altitude] double,"
                                    "[longitude] double,"
                                    "[latitude] double,"
                                    "[speed] double,"
                                    "[bearing] double,"
                                    "[accuracy] double)"
                                    ,nil];
        [db beginTransaction];
        BOOL result = YES;
        for (NSString *sql in sqlArray) {
            result &= [db executeUpdate:sql];
        }
        if (result) {
            result &= [db commit];
        }
        
        if (!result) {
            [db rollback];
        }
    }];
}

- (BOOL)insertRunInfo:(RunInfo *)runInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"insert into runInfo set planId=?,locate_date=?,altitude=?,longitude=?,latitude=?,speed=?,bearing=?,accuracy",
         [NSNumber numberWithLongLong:runInfo.planId],
         [NSNumber numberWithLongLong:runInfo.locate_date],
         [NSNumber numberWithLongLong:runInfo.altitude],
         [NSNumber numberWithLongLong:runInfo.longitude],
         [NSNumber numberWithLongLong:runInfo.latitude],
         [NSNumber numberWithLongLong:runInfo.speed],
         [NSNumber numberWithLongLong:runInfo.bearing],
         [NSNumber numberWithLongLong:runInfo.accuracy]];
        
        if (result) {
            runInfo.dbId = db.lastInsertRowId;
        }
    }];
    return result;
}

- (NSArray *)selectRunInfoWithPlanId:(UInt64)planId
{
    __block NSMutableArray *returnArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from runInfo where planId=?",[NSNumber numberWithLongLong:planId]];
        while (resultSet.next) {
            [returnArray addObject:[RunInfo runInfoWithResultSet:resultSet]];
        }
        [resultSet close];
    }];
    
    return returnArray;
}
@end
